package cn.infozr.api.client;

import cn.infozr.api.util.SM3SignatureUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.TreeMap;

public class BaseClient {
    // 获取药品列表接口地址
    protected static final String API_URL_FRUG_LIST = "http://127.0.0.1:86/ygydapi/v1/getDrugList";

    // 新增药品信息上传接口地址
    protected static final String DRUG_INFO_API_URL = "http://127.0.0.1:86/ygydapi/v1/uploadDrugInfo";
    // 药品入库信息上传接口地址
    protected static final String DRUG_IN_API_URL = "http://127.0.0.1:86/ygydapi/v1/uploadDrugIn";
    // 药品库存信息上传接口地址
    protected static final String DRUG_INVENTORY_API_URL = "http://127.0.0.1:86/ygydapi/v1/uploadDrugInvinfo";
    // 药品出库信息上传接口地址
    protected static final String DRUG_OUT_API_URL = "http://127.0.0.1:86/ygydapi/v1/uploadDrugOut";
    // 温湿度信息上传接口地址
    protected static final String HUMITURE_API_URL = "http://127.0.0.1:86/ygydapi/v1/uploadHumitureInfo";
    // 下属门店管理接口地址
    protected static final String SUB_STORE_API_URL = "http://127.0.0.1:86/ygydapi/v1/editSubStore";
    // 门店基本信息完善接口地址
    protected static final String STORE_INFO_UPDATE_API_URL = "http://127.0.0.1:86/ygydapi/v1/editSubStoreInfo";
    protected static final String APP_ID = "1957363709368844290"; // 替换为实际的appId
    protected static final String SECRET_KEY = "a087723207fc44e880893b8c7c81c174"; // 替换为实际的密钥
    // 药店统一社会信用代码
    protected static final String uscc = "913401007608485412"; // 请替换为实际的统一社会信用代码

    /**
     * 生成数据签名
     * @param request 请求参数对象
     * @return 签名字符串
     * @throws Exception 加密异常
     */
    protected String generateSign(DrugListApiClient.DrugListRequest request) throws Exception {
        // 按照字段名的字典序拼接参数
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", request.getAppId());
        params.put("reqId", request.getReqId());
        params.put("size", request.getSize() == null ? "" : request.getSize().toString());
        params.put("timestamp", request.getTimestamp());


        if (request.getUpdateTime() != null && !request.getUpdateTime().isEmpty()) {
            params.put("updateTime", request.getUpdateTime() == null ? "" : request.getUpdateTime());
        }
        //params.put("timestamp", SECRET_KEY);


        return SM3SignatureUtil.generateSignature(params,SECRET_KEY);
    }

    /**
     * 发送POST请求
     * @param url 请求地址
     * @param request 请求参数对象
     * @return 响应结果
     * @throws Exception 网络异常
     */
    protected String sendPostRequest(String url, DrugListApiClient.DrugListRequest request) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法和请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);

        // 序列化请求参数，过滤空值
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String jsonInputString = objectMapper.writeValueAsString(request);
        System.out.println(jsonInputString);
        // 发送请求
        try(OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        // 读取响应
        try(BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            return response.toString();
        }
    }
}